<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-9-15
 * Time: 14:05
 */

namespace doumiaoduo\ueditor;

use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\db\Query;

class ImageUploadMultipleBehavior extends Behavior
{

    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
            ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
        ];
    }

    public function afterFind($event){
        if(\Yii::$app->controller->action->id == 'update'){
            $imageList = [];
            $altList = [];
            $arr = (new Query())->from('{{%album}}')->where(['object_id'=>$this->owner->id,'class_name'=>$this->owner->className(),'branch_id'=>$this->owner->branch_id])->all();
            foreach($arr as $v){
                $imageList[] = $v['file_path'];
                $altList[] = $v['alt'];
            }
            $this->owner->imageList = implode('#|#',$imageList);
            $this->owner->altList = implode('#|#',$altList);

        }
    }

    public function afterDelete($event){
        \Yii::$app->db->createCommand()->delete('{{%album}}',['object_id'=>$this->owner->id,'class_name'=>$this->owner->className(),'branch_id'=>$this->owner->branch_id])->execute();
    }

    public function afterSave($event){
        $img = [];
        $imageList = $this->owner->imageList;
        $altList = $this->owner->altList;
        $image   = explode('#|#',$imageList);
        $alt = explode('#|#',$altList);
        foreach($image as $k=>$v){
            $img[$k]['file_path']=$v;
            $img[$k]['branch_id']=$this->owner->branch_id;
            $img[$k]['created_at']=$this->owner->created_at;
            $img[$k]['class_name']=$this->owner->className();
            $img[$k]['object_id']=$this->owner->id;
        }
        foreach($alt as $k=>$v){
            $img[$k]['alt'] = $v;
        }
        if(\Yii::$app->controller->action->id == 'create' && $this->owner->type==1){
            if($img!=null){
                \Yii::$app->db->createCommand()->batchInsert('{{%album}}',['file_path','branch_id','created_at','class_name','object_id','alt'],$img)->execute();
            }
        }elseif(\Yii::$app->controller->action->id == 'update' && $this->owner->type==1){
            if($img!=null){
                \Yii::$app->db->createCommand()->delete('{{%album}}',['object_id'=>$this->owner->id,'class_name'=>$this->owner->className(),'branch_id'=>$this->owner->branch_id])->execute();
                \Yii::$app->db->createCommand()->batchInsert('{{%album}}',['file_path','branch_id','created_at','class_name','object_id','alt'],$img)->execute();
            }
        }

    }


}